var localFiles = {};

/*
 * ===========================================
 * Usage: dropzoneS1M.init(
 * 							<callback function when file is dropped to dropzone>, 
 * 							<callback function when file is successfully uploaded>, 
 * 							<ajax file upload action name>,
 * 							<callback function when file is dropped / files are dropped to dropzone>,
 * 						  )
 * ------------------------------------
 * dz.drop --> callback to caller	
 * caller.validate	
 * (validate ok)	
 * caller --> create list item outside of dz	
 * caller --> dz.upload(file A)	
 * dz.Success --> caller.callback	
 * caller --> dz.removefile(A)
 * 
 * ============================================
 */
var dropzoneS1M = (function($){
	"use strict";
	var _fnOnFileAdded, _fnOnFileUploadedSuccessfully, _fnFilesDropped, _fnOnMaxFilesExceeded, _fnOnFileUploadError;
	var _initCalled = false;
	var _uploadFileActionName='';
	var _data = [];
	var _inProcess = 0;
	
	
	var _init = function(callbackAdded, callbackUploadSuccess, uploadFileActionName, callbackFilesDropped, callbackOnMaxFilesExceeded, callbackOnFileUploadError)
	{
		_fnOnFileAdded = callbackAdded;
		_fnOnFileUploadedSuccessfully = callbackUploadSuccess;
		_uploadFileActionName = uploadFileActionName;
		_fnFilesDropped = callbackFilesDropped;
		_fnOnMaxFilesExceeded = callbackOnMaxFilesExceeded;
		_fnOnFileUploadError = callbackOnFileUploadError;
		//----------------------------
		_initCalled = true;
	};
	
	//---------------------------------------------------------------------------------------	
    function generateUUID(){
      var d = performance.now();
      if(window.performance && typeof window.performance.now === "function"){
          d += performance.now(); //use high-precision timer if available
      }
      var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
          var r = (d + Math.random()*16)%16 | 0;
          d = Math.floor(d/16);
          return (c=='x' ? r : (r&0x3|0x8)).toString(16);
      });
      return uuid;
    }

	//---------------------------------------------------------------------------------------	
	
	Dropzone.autoDiscover = false;
		
	var dropzoneCmp = $('.dropzone').dropzone({
		url: "somelink",
		parallelUploads: 100,
		addRemoveLinks: false,
		maxFiles:maxFiles,
		uploadMultiple: false,
		paramName: 'FILE_TO_UPLOAD',
		dictDefaultMessage: resources[IResourceName.DROP_FILES_HERE],
		// Prevents Dropzone from uploading dropped files immediately
		// You should initialize your dropzone with 
		// the autoProcessQueue: false option and call processQueue() on your dropzone object in the ajax callback
		autoProcessQueue: false,
		autoQueue : false,//this param doesn't exist in docs even though it makes some issues
	    success: function (file, response){
	        console.log("- Successfully uploaded -");
	        var responseObj = JSON.parse(response);
	        _data = [];
	        _fnOnFileUploadedSuccessfully(responseObj);
	    },
	    error: function (file, response){
	    	console.log("- Error? -");
	    	var responseObj = JSON.parse(response);
	    	_fnOnFileUploadError(file,responseObj);
      	},		
		
		init: function(){
			
			//------ setup event listeners -----------------
			
			this.on('maxfilesexceeded',function(file){
				console.log('Max File Exceeded!');
				_fnOnMaxFilesExceeded(file);
			});			
			
			this.on("addedfile", function(file){
				console.log("- Added file: Started -");
				if (!_initCalled){
					console.log('Sorry, you didnt call initCallbacks!');
				} 
				_inProcess = this.files.length;
				console.log('Count: '+_inProcess);
				console.log('this.options.maxFiles:'+this.options.maxFiles);
				if (_inProcess > this.options.maxFiles) {
					this.removeFile(file);
					return false;
				}			
				
				var uuid = generateUUID();
				file.previewElement.uuid = uuid;
				localFiles[uuid] = file;
				_fnOnFileAdded(file);
			});

		  this.on("processing", function(file){
			this.options.url = "\scholaroneAJAXServlet?"+IParameterName.TAG_ACTION+"="+_uploadFileActionName;
		  });		
		  
		  this.on("drop", function(event){
			_fnFilesDropped();
		  });		
		  
		  this.on("sending", function(file, xhr, formData){
		    formData.append(IParameterName.AJAX_TOKEN, user.ajaxSecurityToken);
		    formData.append(IParameterName.FILE_UUID, file.previewElement.uuid);
		    var key;
		    for (key in _data) {
		    	formData.append(key,_data[key]);
		    }
		  });
		  this.on("removedfile", function (file){
			  _inProcess =this.files.length;
			  console.log('Count: '+_inProcess);
			  console.log('- File removed from dropzone area -')
		  });		    
		}
	});	
		
	function _fnFileUpload(fileUUID, data, dropzoneDiv){
		if(fileUUID != null && fileUUID.length != 0){
			var file = localFiles[fileUUID];
			_data = data;
			$(dropzoneDiv)[0].dropzone.processFile(file);	
		}
	}
	
	function _fnFileRemove(fileUUID, dropzoneDiv){
		if(fileUUID != null && fileUUID.length != 0 && localFiles[fileUUID]){
			var file = localFiles[fileUUID];
			$(dropzoneDiv)[0].dropzone.removeFile(file);
			delete localFiles[fileUUID];

		}
	}
	
	function _fnGetPendingFileCount()
	{
		return _inProcess;
		
	}
	
	return{
		init : _init,
		uploadFile : _fnFileUpload, 
		removeFile : _fnFileRemove,
		getPendingFileCount : _fnGetPendingFileCount
	};
	
})($);